<template>
  <div >


        <el-card shadow="hover" class="custom-card">
          <div class="card-content">
            <div class="card-left">
              <div class="card-title">
                <i class="el-icon-collection-tag"></i>方向-成果统计矩阵​</div>
              <div ref="barChart" class="chart-container"></div>
            </div>
          </div>
        </el-card>


  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getResearchResultsByDept } from "@/api/sci/patent";



export default {
  name: "DeptAchvs",
  components: {},
  data() {
    return {

      barChart: null
    };
  },
  computed: {

  },
  created() {
  },
  mounted() {
    this.initChart();
  },
  watch: {},
  methods: {

    initChart() {
      // 初始化图表
      this.barChart = echarts.init(this.$refs.barChart);
      this.updateChart();

      // 监听窗口变化，自适应调整图表大小
      window.addEventListener('resize', this.handleResize);
    },
    async updateChart() {
      try {
        const deptMapping = {
        '能源战略与碳中和路径方向': '能源战略',
        '智慧矿山方向': '智慧矿山',
        '新型储能方向': '新型储能',
        '分布式能源方向': '分布式能源',
        '地下清洁能源资源方向': '地清',
        '二氧化碳捕集利用与封存方向': 'CCUS',
        '节能减碳方向': '节能减碳',
        '能源大数据方向': '能源大数据',
        '能源软件平台方向': '能源软件'
      };
        const response = await getResearchResultsByDept();
        const data = response.data;

        // 提取 X 轴（部门名称）并进行映射转换
        const xAxisData = data.map(item => deptMapping[item.dept_name] || item.dept_name);
        // 提取四个系列的数据
        const patentTotalData = data.map(item => item.patent_count_total); // 专利总数
        const paperTotalData = data.map(item => item.paper_count_total);   // 论文总数
        const softwareTotalData = data.map(item => item.software_count_total); // 软著总数
        const standardTotalData = data.map(item => item.standard_count_total); // 标准总数

        const barOption = {
          color: ['#267FF7', '#7AB8FF', '#599EEC', '#3673E8'],
          // tooltip: {
          //   trigger: 'axis',
          //   axisPointer: {
          //     type: 'shadow'
          //   },
          //   formatter: (params) => {
          //     let tooltipText = params[0].name + '<br/>';
          //     let total = 0;

          //     params.forEach(param => {
          //       tooltipText += `${param.marker} ${param.seriesName}: ${param.value}<br/>`;
          //       total += param.value;
          //     });

          //     tooltipText += `总计: ${total}`;
          //     return tooltipText;
          //   }
          // },

          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              crossStyle: {
                color: '#999'
              }
            },
            backgroundColor: 'rgba(38, 127, 247, 0.15)', // 淡蓝色背景
            borderColor: 'rgba(64, 158, 255, 0.3)', // 边框颜色
            borderWidth: 1,
            padding: 10,
            textStyle: {
              color: '#000',
              fontSize: 12
            },
            extraCssText: 'backdrop-filter: blur(10px); border-radius: 8px; box-shadow: 0 0 20px rgba(64, 158, 255, 0.3);',
            formatter: (params) => {
              // 过滤掉undefined或隐藏的数据项
              const validParams = params.filter(param => param && param.value !== undefined && param.value !== null);

              if (validParams.length === 0) {
                return ''; // 如果没有有效数据，不显示tooltip
              }

              let total = 0;
              let tooltipText = `<div style="padding: 8px 12px; background: rgba(255, 255, 255, 0.1); border-radius: 6px; margin-bottom: 8px; font-weight: bold; text-align: center;">${validParams[0].name}</div>`;

              // 定义与图表系列一致的颜色
              const colors = ['#267FF7', '#7AB8FF', '#599EEC', '#3673E8'];

              // 创建卡片数组
              const cards = validParams.map((param, index) => {
                // 处理undefined值，显示为空
                const value = param.value === undefined || param.value === null ? 0 : param.value;
                total += value;

                // 根据有效参数数量动态调整卡片宽度
                let cardWidth;
                if (validParams.length === 1) {
                  cardWidth = '100%'; // 只有一个参数时占满整行
                } else {
                  cardWidth = 'calc(50% - 4px)'; // 多个参数时每行显示两个
                }

                return `<div style="display: inline-block; width: ${cardWidth}; padding: 6px 8px; background: ${colors[index]}; border-radius: 5px; margin: 2px; vertical-align: top; box-sizing: border-box;">
                  <div style="display: flex; align-items: center; justify-content: space-between;">
                    <div style="display: flex; align-items: center;">
                      <span style="display: inline-block; width: 6px; height: 6px; border-radius: 50%; background: ${param.color}; margin-right: 4px;"></span>
                      <span style="color: #ffffff; font-size: 12px; white-space: nowrap;">${param.seriesName}</span>
                    </div>
                    <div style="font-weight: bold; font-size: 14px; color: #ffffff; text-shadow: 0 0 4px rgba(255, 255, 255, 0.8); margin-left: 4px;">
                      ${value}
                    </div>
                  </div>
                </div>`;
              });

              // 根据有效参数数量组织行显示
              if (cards.length === 1) {
                tooltipText += `<div>${cards[0]}</div>`;
              } else if (cards.length === 2) {
                tooltipText += `<div>${cards[0]}${cards[1]}</div>`;
              } else if (cards.length === 3) {
                tooltipText += `<div style="margin-bottom: 4px;">${cards[0]}${cards[1]}</div>`;
                tooltipText += `<div>${cards[2]}</div>`;
              } else if (cards.length === 4) {
                tooltipText += `<div style="margin-bottom: 4px;">${cards[0]}${cards[1]}</div>`;
                tooltipText += `<div>${cards[2]}${cards[3]}</div>`;
              }

              // 只有当有有效数据时才显示总数行
              if (validParams.length > 0) {
                // 添加总数行
                tooltipText += `<div style="padding: 6px 10px; background: #1890FF; border-radius: 5px; display: flex; justify-content: space-between; align-items: center; margin-top: 8px;">
                  <div>
                    <span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: #ffffff; margin-right: 6px;"></span>
                    <span style="color: #ffffff; font-weight: bold;">成果总数</span>
                  </div>
                  <span style="font-weight: bold; font-size: 14px; color: #ffffff; text-shadow: 0 0 4px rgba(255, 255, 255, 0.8); margin-left: 15px;">${total}</span>
                </div>`;
              }

              return tooltipText;
            },
            position: (point, params, dom, rect, size) => {
              // 获取鼠标位置
              const x = point[0];
              const y = point[1];

              // 获取tooltip尺寸
              const tooltipWidth = size.contentSize[0];
              const tooltipHeight = size.contentSize[1];

              // 获取视图尺寸
              const viewWidth = size.viewSize[0];
              const viewHeight = size.viewSize[1];

              // 默认位置（在鼠标右侧）
              let posX = x + 15;
              let posY = y - tooltipHeight / 2;

              // 如果右侧空间不足，显示在左侧
              if (posX + tooltipWidth > viewWidth) {
                posX = x - tooltipWidth - 15;
              }

              // 如果上方空间不足，向下调整
              if (posY < 0) {
                posY = y + 15;
              }

              // 如果下方空间不足，向上调整
              if (posY + tooltipHeight > viewHeight) {
                posY = viewHeight - tooltipHeight - 10;
              }

              // 确保不会超出左边界
              if (posX < 0) {
                posX = 10;
              }

              return [posX, posY];
            }
          },
          legend: {
            data: ['专利', '论文', '软著', '标准'],
            bottom: '0',
            left: 'center'
          },
          grid: {
            left: '5%',
            right: '5%',
            bottom: '20%',
            top: '5%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: xAxisData,
            axisLabel: {

              fontSize: 10,
              margin: 20
            }
          },
          yAxis: {
            type: 'value',
            minInterval: 1 ,// 确保Y轴显示整数

          },
          series: [
            {
              name: '专利',
              type: 'bar',
              stack: '总量', // 设置为堆叠图
              barMaxWidth: 40,
              data: patentTotalData,

            },
            {
              name: '论文',
              type: 'bar',
              stack: '总量', // 设置为堆叠图
              barMaxWidth: 40,
              data: paperTotalData,

            },
            {
              name: '软著',
              type: 'bar',
              stack: '总量', // 设置为堆叠图
              barMaxWidth: 40,
              data: softwareTotalData,

            },
            {
              name: '标准',
              type: 'bar',
              stack: '总量', // 设置为堆叠图
              barMaxWidth: 40,
              data: standardTotalData,

            }
          ]
        };

        this.barChart.setOption(barOption, true); // 使用 true 表示合并配置
      } catch (error) {
        console.error('获取各方向成果数据失败:', error);
        this.$message.error('无法加载各方向成果数据');
      }
    },


    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    }
  },

  beforeDestroy() {
    // 销毁图表实例，防止内存泄漏
    if (this.chart) {
      this.chart.dispose();
    }
    window.removeEventListener('resize', this.handleResize);
  }
};
</script>

<style lang="scss" scoped>

  .chart-container {
    width: 100%;
    height: 200px;
  }

  .custom-card {
    border-radius: 8px;
    border: none;

    ::v-deep .el-card__body {
      padding: 20px;
    }
  }

  .card-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-left {
    flex: 1;
  }

   .card-title {
    color: #000000;
    font-size: 22px;
    margin-bottom: 16px;
    font-weight: bold; /* Changed to bold */
    font-family: SimHei, sans-serif; /* Added SimHei font */
    display: flex;
    align-items: center;
    gap: 15px;
  }






</style>
